package com.binguo.api.baidu;

import com.binguo.api.baidu.model.ProductSubDbForm;
import com.binguo.api.businessmodel.ProductImgDetailModel;
import com.binguo.api.businessmodel.ProductImgModel;

import com.binguo.api.schedule.DataLoadService;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.*;
import com.binguo.common.util.ImageBase64Util;
import com.binguo.model.api.dto.OrderDTO;
import com.binguo.model.api.dto.OrderItemDTO;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.repository.ProductRepository;
import com.binguo.model.repository.ProductSubRepository;
import com.binguo.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CorrectService {

    private static Logger logger = LoggerFactory.getLogger(CorrectService.class);


    @Autowired
    private BaiduRecUtil baiduRecUtil;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ProductSubRepository productSubRepository;

    @Autowired
    private ProductService productService;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductSubMapper productSubMapper;

    @Resource
    private LogProductImgMapper logProductImgMapper;
    @Resource
    private LogProductImgFromUserMapper logProductImgFromUserMapper;
    @Resource
    private CashierDeskMapper cashierDeskMapper;
    @Resource
    private ShopBaiduUrlCurMapper shopBaiduUrlCurMapper;

    public void correctProductImg(OrderDTO orderDTO, ProductImgModel productImgModel, Integer branchId) {

        if (orderDTO.getProductOrderNo() == null || StringUtils.isEmpty(orderDTO.getProductOrderNo())) {
            return;
        }

        logger.info("===============start =====correctProductImg");
        try {
            if (productImgModel == null) {
                return;
            }

            logger.info("===============start =====productImgModel.getItemList()====" + productImgModel.getItemList());
            if (productImgModel.getItemList() != null && productImgModel.getItemList().size() > 0) {
                int i = 0;

                Map<String, ProductImgDetailModel> seqProductImgDetailModelMap = new HashMap<>();

                for (ProductImgDetailModel productImgDetailModel : productImgModel.getItemList()) {
                    seqProductImgDetailModelMap.put(productImgDetailModel.getSeq().toString(), productImgDetailModel);
                }


                Set<Integer> ypProductRefproductIdList = null;
                if(DataLoadService.shopYpProductListMap != null){
                    List<ProductYpRef> temp = DataLoadService.shopYpProductListMap.get(productImgModel.getShopId());

                    if (temp != null && temp.size() > 0) {
                        ypProductRefproductIdList = temp.stream().map(ProductYpRef::getProductId).collect(Collectors.toSet());
                    }
                }


                for (OrderItemDTO orderItemDTO : orderDTO.getItems()) {
                    logger.info("===============start =====orderItemDTO.getChange()====" + orderItemDTO.getChange());
                    if (orderItemDTO.getChange() != null && orderItemDTO.getChange().equals("1")) {

                        ProductImgDetailModel productImgDetailModel = seqProductImgDetailModelMap.get(orderItemDTO.getSeq());

                        Object isAdded = baiduRecUtil.getKey(productImgModel.getProductOrderNo() + orderItemDTO.getSeq());
                        if (isAdded != null) {
                            continue;
                        }
                        //有变化
                        if (orderItemDTO.getProductId() != null && !orderItemDTO.getProductId().equals(productImgDetailModel.getProductId())) {
                            if (ypProductRefproductIdList != null && ypProductRefproductIdList.contains(orderItemDTO.getProductId())) {
                                logger.info("忽略云澎菜品库商品:" + orderItemDTO.getProductId());
                                continue;
                            }

                            if (productImgDetailModel.getScore() > 0.75) {
                                Integer oldProductId = productImgDetailModel.getProductId();
                                if (oldProductId != 1) {
                                    logger.info("被修改的菜品分数大于0.75,删除旧图片oldProductId=" + oldProductId);
                                    ThreadManager.executorService.submit(() -> {
                                        if (oldProductId != null) {
                                            baiduRecUtil.deleteProductImgCur(oldProductId);
                                        }
                                    });
                                }
                            }


                            String localFilepath = "/usr/local/nginx/html/img/" + productImgModel.getShopId();

                            File shopFile = new File(localFilepath);
                            if (!shopFile.exists()) {
                                shopFile.mkdir();
                            }

                            localFilepath = localFilepath + "/" + orderItemDTO.getProductId();

                            File imgCutFile = new File(localFilepath);
                            if (!imgCutFile.exists()) {
                                imgCutFile.mkdir();
                            }
                            localFilepath += "/temp";

                            File imgCutFileTemp = new File(localFilepath);
                            if (!imgCutFileTemp.exists()) {
                                imgCutFileTemp.mkdir();
                            }

                            StringBuffer cutImgUrl = new StringBuffer("http://")
                                    .append(baiduRecUtil.ipAddress)
                                    .append(":8019/img/")
                                    .append(productImgModel.getShopId())
                                    .append("/")
                                    .append(orderItemDTO.getProductId())
                                    .append("/temp/")
                                    .append(productImgModel.getUuidFileName())
                                    .append("_cut")
                                    .append(i)
                                    .append(".png");


                            String cutImgPath = localFilepath + "/" + productImgModel.getUuidFileName() + "_cut" + i + ".png";
                            i++;

                            String sourceFilePath = productImgModel.getSourceFilename();
                            String sourceFilePathOnNet = productImgModel.getSourceImgOnInternet();

                            if (productImgModel.getCurIpAddress() != null &&
                                    productImgModel.getCurIpAddress().equals(baiduRecUtil.ipAddress)
                                    ) {
                                logger.info("source file ip : {}, sourceFilePath:", productImgModel.getCurIpAddress(), sourceFilePath);
                            } else {
                                logger.info("source file ip : {}", productImgModel.getCurIpAddress());

                                String downloadNetFilepath = "/usr/local/nginx/html/img/" + productImgModel.getShopId() + "/" + orderItemDTO.getProductId() + "/net";

                                File downloadNetFilepathFile = new File(downloadNetFilepath);
                                if (!downloadNetFilepathFile.exists()) {
                                    downloadNetFilepathFile.mkdir();
                                }

                                int tempInt = new Random(100).nextInt();
                                downloadNetFilepath += "/" + productImgModel.getUuidFileName() + "." + tempInt + ".png";
                                ImageBase64Util.downloadNetImage(productImgModel.getSourceImgOnInternet(), downloadNetFilepath);

                                logger.info("source file ip : {}, sourceFilePath:{}",
                                        productImgModel.getCurIpAddress(), downloadNetFilepath);
                                sourceFilePath = downloadNetFilepath;

                                StringBuffer temp = new StringBuffer("http://")
                                        .append(baiduRecUtil.ipAddress)
                                        .append(":8019/img/")
                                        .append(productImgModel.getShopId())
                                        .append("/")
                                        .append(orderItemDTO.getProductId())
                                        .append("/net/")
                                        .append(productImgModel.getUuidFileName())
                                        .append(".")
                                        .append(tempInt)
                                        .append(".png");

                                sourceFilePathOnNet = temp.toString();
                            }

                                try {
                                    ImageUtil.cutImage(sourceFilePath, cutImgPath
                                            , productImgDetailModel.getLeft(),
                                            productImgDetailModel.getTop(), productImgDetailModel.getWidth(), productImgDetailModel.getHeight());
                                    logger.info("===============cutImgPath==" + cutImgPath);

//                                    Integer branchId = null;
                                    Product p = baiduRecUtil.productMapper.selectByPrimaryKey(orderItemDTO.getProductId());
                                    if (p != null) {
                                        branchId = p.getStoreid();
                                    }

                                    String contSign = baiduRecUtil.addImg(productImgModel.getShopId(), cutImgPath,
                                            productImgModel.getShopId() + "_" + orderItemDTO.getProductId(), branchId);

                                    logger.info("===============contSign==" + contSign);
                                    List<Map<String, String>> contSignCurList = null;
                                    if (DataLoadService.shopBaiduUrlCurListMap != null
                                            && DataLoadService.shopBaiduUrlCurListMap.get(productImgModel.getShopId()) != null) {
                                        /*contSingCur = baiduRecUtil.addImgCur(productImgModel.getShopId(), cutImgPath,
                                                productImgModel.getShopId() + "_" + orderItemDTO.getProductId(), branchId);*/
                                        contSignCurList = baiduRecUtil.addImgCurList(productImgModel.getShopId(), cutImgPath,
                                                productImgModel.getShopId() + "_" + orderItemDTO.getProductId(), branchId);
                                    }

                                    logger.info("===============contSingCur==" + contSignCurList);
                                    if (contSign != null) {
                                        LogProductImgFromUser logProductImgFromUser = new LogProductImgFromUser();
                                        logProductImgFromUser.setContSign(contSign);
                                        logProductImgFromUser.setCreateTime(new Date());
                                        logProductImgFromUser.setCutImg(cutImgPath);
                                        logProductImgFromUser.setSourceImg(productImgModel.getSourceFilename());
                                        logProductImgFromUser.setProductId(orderItemDTO.getProductId());
                                        logProductImgFromUser.setShopId(productImgModel.getShopId());
                                        logProductImgFromUser.setFromCorrect(1);
                                        logProductImgFromUser.setBaiduDeleted(0);
                                        logProductImgFromUser.setImgCutNetUrl(cutImgUrl.toString());
                                        logProductImgFromUser.setImgSrcNetUrl(sourceFilePathOnNet);
                                        logProductImgFromUser.setSubDb(0);


                                        baiduRecUtil.logProductImgFromUserMapper.insert(logProductImgFromUser);
                                        if (productImgDetailModel.getProductId().intValue() == 1) {
                                            //未识别菜品
                                            addWxProductImg(orderItemDTO.getProductId(), p.getShopid(), p.getStoreid(),sourceFilePathOnNet, contSign);
                                        }

                                        baiduRecUtil.setKey(productImgModel.getProductOrderNo() + orderItemDTO.getSeq(), "1", 60 * 1000);
                                    }


                                    if (contSignCurList != null && contSignCurList.size() > 0) {
                                        for (Map<String, String> map : contSignCurList) {
                                            String appid = map.get("appid");
                                            String contSignCur = map.get("contSign");
                                            LogProductImgFromUser logProductImgFromUser = new LogProductImgFromUser();
                                            logProductImgFromUser.setContSign(contSignCur);
                                            logProductImgFromUser.setCreateTime(new Date());
                                            logProductImgFromUser.setCutImg(cutImgPath);
                                            logProductImgFromUser.setSourceImg(productImgModel.getSourceFilename());
                                            logProductImgFromUser.setProductId(orderItemDTO.getProductId());
                                            logProductImgFromUser.setShopId(productImgModel.getShopId());
                                            logProductImgFromUser.setFromCorrect(1);
                                            logProductImgFromUser.setBaiduDeleted(0);
                                            logProductImgFromUser.setImgCutNetUrl(cutImgUrl.toString());
                                            logProductImgFromUser.setImgSrcNetUrl(sourceFilePathOnNet);
                                            logProductImgFromUser.setSubDb(1);
                                            logProductImgFromUser.setBaiduAppId(appid);


                                            baiduRecUtil.logProductImgFromUserMapper.insert(logProductImgFromUser);
                                        }

                                        Condition productSubCondition = new Condition(ProductSub.class);
                                        productSubCondition.or().andEqualTo("productId", orderItemDTO.getProductId());

                                        List<ProductSub> productSubList = baiduRecUtil.productSubMapper.selectByCondition(productSubCondition);

                                        if (productSubList == null || productSubList.size() == 0) {
                                            ProductSub productSub = new ProductSub();
                                            productSub.setBranchId(branchId);
                                            productSub.setShopId(productImgModel.getShopId());
                                            productSub.setCreateTime(new Date());
                                            productSub.setProductId(orderItemDTO.getProductId());

                                            baiduRecUtil.productSubMapper.insertSelective(productSub);
                                        }
                                    }

                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }




                        }

                    }
                }
            }

            logger.info("===============end=====correctProductImg");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public Integer handleNoSettedProduct(String productOrderNo, OrderItemDTO orderItemDTO, ProductImgDetailModel productImgDetailModel, Integer branchId, Integer shopId){

        Object isAdded = baiduRecUtil.getKey(productOrderNo + orderItemDTO.getSeq());
        if (isAdded != null) {
            return null;
        }

        String productName = PriceUtil.changeF2Y(orderItemDTO.getPrice()) + "元菜品";
            //未识别菜品

        return addProduct(orderItemDTO.getPrice(), branchId, shopId, productName);

    }

    private Integer addProduct(Long price, Integer branchId, Integer shopId, String productName) {
        Condition productCondition = new Condition(Product.class);
        productCondition.or().andEqualTo("shopid", shopId)
                .andEqualTo("name", productName)
                .andEqualTo("deleted", false)
                .andEqualTo("storeid", branchId)
        ;
        List<Product> productList = productMapper.selectByCondition(productCondition);

        if (productList != null && productList.size() > 0) {
            //商品已存在
            Integer productId = productList.get(0).getId();

            addSubDb(shopId, branchId, productId);

            return productId;
        }

        Product product = new Product();
        product.setName(productName);
        product.setUpdated(new Date());
        product.setCreated(product.getUpdated());
        product.setDeleted(false);
        product.setSearchcode(System.currentTimeMillis() + "");
        product.setStatus(new Byte("1"));
        product.setVipprice(price);
        product.setPrice(price);
        product.setStoreid(branchId);
        product.setShopid(shopId);
        product.setProductType(1);

        productRepository.save(product);


        if (DataLoadService.shopBaiduUrlCurListMap != null && DataLoadService.shopBaiduUrlCurListMap.get(shopId) != null) {
            ProductSub productSub = new ProductSub();
            productSub.setProductId(product.getId());
            productSub.setCreateTime(new Date());
            productSub.setShopId(shopId);
            productSub.setBranchId(branchId);

            productSubRepository.save(productSub);
        }

        productService.addShopProductVersion(product.getShopid());

        return product.getId();
    }

    private void addWxProductImg(Integer productId, Integer shopId, Integer branchId, String productImg, String contSign){
        LogProductImg logProductImg = new LogProductImg();
        logProductImg.setBaiduDeleted(0);
        logProductImg.setBranchId(branchId);
        logProductImg.setShopId(shopId);
        logProductImg.setProductId(productId);
        logProductImg.setFromWxUpload(1);
        logProductImg.setCreateTime(new Date());
        logProductImg.setImgCutNetUrl(productImg);
        logProductImg.setImgSrcNetUrl(productImg);
        logProductImg.setSourceImg(productImg);
        logProductImg.setContSign(contSign);
        logProductImg.setCutImg(productImg);
        logProductImgMapper.insertSelective(logProductImg);
    }

    private void addSubDb(Integer shopId, Integer branchId, Integer productId){
        String url = "https://binguoai.com/api/wxapp/updateProductSubDb";

        ThreadManager.executorService.execute(()->{
            HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
            MediaType jsontype = MediaType.APPLICATION_JSON;
            DEFAULT_JSON_HEADER.setContentType(jsontype);

            ProductSubDbForm productSubDbForm = new ProductSubDbForm();
            productSubDbForm.setBranchId(branchId);
            productSubDbForm.setShopId(shopId);
            productSubDbForm.setProductIdList(new ArrayList<>());
            productSubDbForm.getProductIdList().add(productId);

            String requestBody = com.alibaba.fastjson.JSONObject.toJSON(productSubDbForm).toString();

            logger.info("corrrect service add img requestBody=======" + requestBody);
            try {
                HttpEntity<String> entity = new HttpEntity<>(requestBody, DEFAULT_JSON_HEADER);

                ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

                logger.info("corrrect service add img result=======" + result.getBody());
            } catch (Exception e) {

            }
        });
    }

}
